/** 分离出来的查询数据库逻辑 */
import mysql from 'mysql';
/** 数据库配置信息 */
import dbconfig from './database';
let pool = null;

/** 初始化数据库连接 */
export const init = () => {
    pool = mysql.createPool(dbconfig.connection);
    /** 选中数据库 */
    pool.query('USE ' + dbconfig.database);
}

/** 查询数据库封装 */
export const execQuery = (sql, args) => {
    return new Promise((res, rej) => {
        pool.getConnection((error, connection) => {
            if (error) throw error;
            // 查询参数
            // 执行查询
            connection.query(
                sql,
                args || [],
                (error, results) => {
                    error && rej(error);
                    // 处理结果
                    res(results);
                });
            // 返回连接池
            connection.release((error) => error && rej(error));
        });
    })
};

/** 获取用户列表 */
export const getUserList = (params) => {
    return new Promise(async (resolve, reject) => {
        let sql = "SELECT * FROM user_list";
        /** 查询语句 */
        execQuery(sql, params).then(resolve).catch(reject);
    })
}

/** 获取汽车列表 */
export const getCarList = (params) => {
    return new Promise(async (resolve, reject) => {
        let sql = "SELECT * FROM car_list";
        /** 查询语句 */
        execQuery(sql, params).then(resolve).catch(reject);
    })
}

/** 获取单个汽车详情 */
export const getCarById = (params) => {
    return new Promise(async (resolve, reject) => {
        let sql = "SELECT * FROM car_list WHERE id = ?";
        /** 查询语句 */
        execQuery(sql, params).then(resolve).catch(reject);
    })
}